package com.sylingd.blog.lib

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.webkit.*
import com.sylingd.blog.activity.ListActivity
import com.sylingd.blog.activity.ReadActivity
import com.sylingd.blog.activity.PhotoActivity
import java.io.ByteArrayInputStream
import java.lang.ref.WeakReference


class WebViewBridge(
		getActivity: Activity,
		private val mWebView: WebView,
		mClient: Client?) {

	private var client: Client
	private val mActivity = WeakReference(getActivity)

	init {
		mWebView.settings.javaScriptEnabled = true
		mWebView.settings.domStorageEnabled = true
		mWebView.addJavascriptInterface(this, "SYBridge")
		client = mClient ?: Client()
		client.mActivity = mActivity
		mWebView.webViewClient = client
	}

	//显示多个大图片
	@JavascriptInterface
	fun showBigImage(urls: String, currentIndex: Int) {
		val act = mActivity.get()
		if (act != null) {
			val urlsArr = when {
				urls.contains("|") -> urls.split("|") as ArrayList<String>
				else -> arrayListOf(urls)
			}
			PhotoActivity.launch(act, urlsArr, currentIndex)
		}
	}

	//显示列表页面
	@JavascriptInterface
	fun showList(type: String, value: String) {
		val act = mActivity.get()
		if (act != null) {
			when (type) {
				"id" -> {
					ListActivity.launch(act, value.toInt())
				}
				"tag" -> {
					ListActivity.launch(act, value)
				}
			}
		}
	}

	open class Client: WebViewClient() {

		var mActivity = WeakReference<Activity>(null)

		override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
			val act = mActivity.get()
			if (act != null) {
				val url = request?.url.toString()
				if (Config.isArticle(url)) {
					val id = Config.getArticleId(url)
					ReadActivity.launch(act, id)
				} else {
					val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
					act.startActivity(intent)
				}
			}
			return true
		}

		override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
			val url = request?.url.toString()
			if (url.startsWith("https://android_assets/")) {
				val resourceType= when {
					url.endsWith(".js") -> "application/javascript"
					url.endsWith(".css") -> "text/css"
					else -> "plain/text"
				}
				val localUrl = "pub_" + url.substring(23)
				try {
					return WebResourceResponse(
							resourceType,
							"utf-8",
							mActivity.get()?.assets?.open(localUrl) ?: ByteArrayInputStream("".toByteArray()))
				} catch (e: Exception) {
					return WebResourceResponse(
							"plain/text",
							"utf-8",
							ByteArrayInputStream("".toByteArray()))
				}
			}
			return super.shouldInterceptRequest(view, request)
		}
	}
}